package com.triones.api.service.interlace.impl;

import cn.hutool.core.io.IoUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.config.InterlaceConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.filter.RepeatedlyRequestWrapper;
import com.ruoyi.common.utils.InterlaceSignature;
import com.triones.api.service.interlace.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

/**
 * interlace 回调通知
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InterlaceWebhookServiceImpl implements InterlaceWebhookService {

    private final InterlaceConfig interlaceConfig;

    private final AsyncWebhookService asyncWebhookService;

    @Override
    public Map<String, Boolean> interlaceWebhook(HttpServletRequest request) {
        Map<String, Boolean> result = new HashMap<>();
        result.put("received", true);
        try {
            String url = request.getMethod() + " " + request.getRequestURI();
            String jsonParam = "";
            if (request instanceof RepeatedlyRequestWrapper) {
                BufferedReader reader = request.getReader();
                jsonParam = IoUtil.read(reader);
            }
            log.info("interlace webhooke回调信息 => URL{},参数类型[json],参数:{}", url, jsonParam);
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> jsonMap = objectMapper.readValue(jsonParam, Map.class);
            if (jsonMap != null) {
                Map<String, Object> dataMap = (Map<String, Object>) jsonMap.get("data");
                String sign = (String) jsonMap.get("sign");
                String businessType = jsonMap.get("businessType").toString();
                if (dataMap != null) {
                    String bytesToHex = InterlaceSignature.bytesToHex(InterlaceSignature.sign(InterlaceSignature.joinStr(dataMap), interlaceConfig.getClientSecret()));
                    log.info("内部签名：{}", bytesToHex);
                    if (!bytesToHex.equals(sign)) {
                        result.put("received", false);
                        return result;
                    }
                    switch (businessType) {
                        /** 账户已注册 */
                        case "AccountRegistered":
                            asyncWebhookService.accountRegistered(dataMap);
                            break;
                        /** kyc */
                        case "KYC":
                            asyncWebhookService.kyc(dataMap);
                            break;
                        /** 加密钱包通知 */
                        case "CryptoConnectWallet":
                            asyncWebhookService.cryptoConnectWallet(dataMap);
                            break;
                        /** 提币 */
                        case "AssetsWithdrawal":
                            asyncWebhookService.assetsWithdrawal(dataMap);
                            break;
                        /** 充值 */
                        case "AssetsDeposit":
                            asyncWebhookService.assetsDeposit(dataMap);
                            break;
                        /** 创建持卡人 */
                        case "CardHolder":
                            asyncWebhookService.cardHolder(dataMap);
                            break;
                        /** 预算交易 */
                        case "BudgetTransaction":
                            asyncWebhookService.budgetTransaction(dataMap);
                            break;
                        /** 创建卡片 */
                        case "CreateCard":
                            asyncWebhookService.createCard(dataMap);
                            break;
                        /** 卡交易 */
                        case "CardTransaction":
                            asyncWebhookService.cardTransaction(dataMap);
                            break;
                        /** 卡状态改变 */
                        case "CardStateChange":
                            asyncWebhookService.cardStateChange(dataMap);
                            break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("e = " + e);
            throw new ServiceException(e.getMessage());
        }
        return result;
    }
}
